package socks

import (
	"fmt"
	"net"
	"time"
)

type SocketClient struct {
	sockBase
	connection *SockConn
	connAddr   string
	isOpen     bool
}

func (c *SocketClient) GetConnection() *SockConn {
	return c.connection
}

func (c *SocketClient) doConnect() error {
	conn, err := net.Dial("tcp", c.connAddr)
	if err == nil {
		c.connection.setConn(conn)
		process_connection(c, c.connection)
	}
	return err
}
func (c *SocketClient) Open() error {
	if !c.isOpen {
		c.isOpen = true

		go func() {
			for c.isOpen {
				if !c.Connected() {
					if err := c.doConnect(); err != nil {
						c.procSockError(nil, fmt.Errorf("SocketClient connect error: %s", err))
					}
				}
				time.Sleep(time.Second)
			}
		}()
	}
	return nil
}

func (c *SocketClient) Close() {
	if c.isOpen {
		c.isOpen = false
		c.connection.Disconnect()
	}
}

func (c *SocketClient) Connected() bool {
	return !c.connection.isClose.Load()
}

func (c *SocketClient) SendQueueDatas() {
	c.connection.SendQueueDatas()
}

// override

func NewSocketClient(addr string) *SocketClient {
	client := &SocketClient{
		connection: createSocketConnection(nil),
		connAddr:   addr,
	}
	return client
}
